#include "threadpool.h"

//********************************************************************************
//推送文件函数
//********************************************************************************
void PushFile(int peerfd,char* filename,pThread_pool_t p)
{
    //1.发送文件长度
    int flag = 200;
    char* md5;
    //1.1获取当前pwd下，文件名为filename的md5值，然后打开实际文件
    OPEN_MYSQL(mysql);
    md5 = Getmd5(mysql,hashmap_get_int(p->userPeerfdHash,peerfd),filename);
    CLOSE_MYSQL(mysql);
    int fd = open(md5,O_RDWR);
    if(fd == -1)
    {
        printf("error filename\n");
        flag = 404;
    }
    send(peerfd,&flag,4,MSG_WAITALL);
    struct stat st;
    fstat(fd,&st);
    send(peerfd,&st.st_size,8,MSG_WAITALL);

    //2.发送文件内容,大文件传输优化
    size_t filelength = st.st_size;
    int spipe[2];
    pipe(spipe);
    while(filelength > 0)
    {
        int len = splice(fd,NULL,spipe[1],NULL,4096,SPLICE_F_MORE);
        splice(spipe[0],NULL,peerfd,NULL,len,SPLICE_F_MORE);
        filelength -= len;
    }
    close(fd);
}

